#include <QCoreApplication>
#include <QDebug>
#include <QTcpSocket>
#include <QTcpServer>

#include "rfb/rfb_data_process.h"

int main(int argc, char **argv)
{
    QCoreApplication a(argc, argv);
    RfbDataProcesser processer;

    QByteArray serverData;
    QTcpSocket *vnc_client = nullptr;

    QTcpSocket vnc;
    QObject::connect(&vnc, &QTcpSocket::readyRead, [&]() {
        serverData = vnc.readAll();
        processer.writeServerData(serverData.data(), serverData.length());

        if (vnc_client) {
            vnc_client->write(serverData);
            serverData.clear();
        }
    });
    vnc.connectToHost("10.20.22.33", 5903);

    QTcpServer vnc_server;
    QObject::connect(&vnc_server, &QTcpServer::newConnection, [&]() {
        while (vnc_server.hasPendingConnections()) {
            vnc_client = vnc_server.nextPendingConnection();
            if (!vnc_client) {
                return;
            }

            QObject::connect(vnc_client, &QTcpSocket::readyRead, [&, vnc_client]() {
                QByteArray data = vnc_client->readAll();
                processer.writeClientData(data.data(), data.length());
                if (vnc.isOpen()) {
                    vnc.write(data);
                }
            });
            QObject::connect(vnc_client, &QTcpSocket::disconnected, [&, vnc_client]() {
                char stop = 129;
                processer.writeServerData(&stop, 1);
            });

            if (!serverData.isEmpty()) {
                vnc_client->write(serverData);
                serverData.clear();
            }
        }
    });

    vnc_server.listen(QHostAddress("10.20.22.98"), 10101);

    return a.exec();
}
